<template>
    <el-dialog v-model="show"
        :title="(props.initList?.type == 1 ? '简配' : props.initList?.type == 2 ? '中配' : '高配') + '配置'" width="20%"
        align-center @close="handleClose" destroy-on-close>
        <el-tree class="tree-border" :data="menuOptions" default-expand-all show-checkbox ref="menuRef" node-key="id"
            :props="{ label: 'name', children: 'children' }"></el-tree>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="handleSubmit" v-loading="loading">确 定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { saveConfig } from '@/api/portfolioManagement/index'
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps(['visible', 'initList']);
const emits = defineEmits(['submit', 'close']);
const loading = ref(false);
const show = ref(false)
const menuOptions: any = ref([])
const menuRef = ref<any>(null);
watch(() => props.visible, (val) => {
    show.value = val;
    if (val) {
        menuOptions.value = props.initList?.detail;
        setTimeout(() => {
            if (props.initList?.choose.length != 0) {
                menuRef.value?.setCheckedKeys(props.initList?.choose);
            }
        }, 100)
    }
}, { immediate: true });

const handleClose = () => {
    emits('close');
};

const handleSubmit = async () => {
    const menuIds = getMenuAllCheckedKeys()
    try {
        loading.value = true;
        await saveConfig({
            id: props.initList?.id,
            dataList: menuIds.map((item: any) => {
                return {
                    settingType: props.initList?.type,
                    attributeId: item
                }
            })
        })

        proxy?.$modal.msgSuccess('操作成功');
        emits('submit', true);
        loading.value = false;
        handleClose()
    } catch (error) {
        loading.value = false;

    }
    // 

}

/** 所有菜单节点数据 */
const getMenuAllCheckedKeys = (): any => {
    const checkedNodes = menuRef.value?.getCheckedNodes() || [];
    const leafNodes = checkedNodes.filter((node: any) => !node.children || node.children.length === 0);
    return leafNodes.map((node: any) => node.id);
}


onMounted(() => {
})
</script>

<style lang="scss" scoped></style>